package com.xunker.appointment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunker.appointment.exception.AppointmentException;
import com.xunker.appointment.mapper.ScheduleMapper;
import com.xunker.appointment.model.hospital.BookingRule;
import com.xunker.appointment.model.hospital.Department;
import com.xunker.appointment.model.hospital.Hospital;
import com.xunker.appointment.model.schedule.Schedule;
import com.xunker.appointment.repository.DepartmentRepository;
import com.xunker.appointment.repository.HospitalRepository;
import com.xunker.appointment.repository.ScheduleRepository;
import com.xunker.appointment.result.ResultCodeEnum;
import com.xunker.appointment.service.DepartmentService;
import com.xunker.appointment.service.HospitalService;
import com.xunker.appointment.service.ScheduleService;
import com.xunker.appointment.vo.hospital.*;
import com.xunker.appointment.vo.order.ScheduleOrderVo;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl extends ServiceImpl<ScheduleMapper,Schedule> implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Override
    public void save(Map<String, Object> objectMap) {
        final String s = JSONObject.toJSONString(objectMap);
        final Schedule schedule = JSONObject.parseObject(s, Schedule.class);
        final Object id = objectMap.get("id");
        final Object hospitalCode = objectMap.get("hospitalCode");
        Schedule schedule_1=scheduleRepository.getScheduleByIdAndHospitalCode(id,hospitalCode);
        schedule.setUpdateTime(new Date());
        schedule.setDeleted(0);
        if(schedule_1==null) {
            schedule.setCreateTime(new Date());
            scheduleRepository.insert(schedule);
        }else {
            scheduleRepository.deleteScheduleByIdAndHospitalCode(id,hospitalCode);
            scheduleRepository.save(schedule);
        }
    }

    @Override
    public Page<Schedule> getByHospitalCode(String hospitalCode, int page, int limit) {
        //创建Pageable对象，设置当前页码和记录数
        Pageable pageable= PageRequest.of(page-1,limit);
        //创建Schedule对象
        Schedule schedule = new Schedule();
        schedule.setDeleted(0);
        schedule.setHospitalCode(hospitalCode);
        //创建Example对象，数据库条件查询
        ExampleMatcher matcher=ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        Example<Schedule> example=Example.of(schedule,matcher);
        Page<Schedule> content=scheduleRepository.findAll(example,pageable);
        return content;
    }

    @Override
    public void remove(String id) {
        scheduleRepository.deleteById(Long.parseLong(id));
    }

    @Override
    public Set<DoctorVo> getDoctorByHD(String hospitalCode, String departmentCode) {
        //1.查询
        Criteria criteria=Criteria.where("hospitalCode").is(hospitalCode).and("departmentCode").is(departmentCode);
        Aggregation aggregation= Aggregation.newAggregation(Aggregation.match(criteria));
        Set<DoctorVo> doctorVoSet=new HashSet<>();
        List<DoctorVo> aggregate =  mongoTemplate.aggregate(aggregation, Schedule.class, DoctorVo.class).getMappedResults();
        aggregate.stream().forEach(s->doctorVoSet.add(s));
        //2.整理
        return doctorVoSet;
    }

    @Override
    public Map<String,Object> getScheduleByHDN(String hospitalCode, String departmentCode, String doctorName) {
        Map<String,Object> map=new HashMap<>();
        //1.查询
        Criteria criteria=Criteria.where("hospitalCode").is(hospitalCode).and("departmentCode").is(departmentCode).and("doctorName").is(doctorName);
        //2.分组计算
        Aggregation aggregation= Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate","doctorName","workTime","amount")
                        .first("workDate").as("workDate")
                        .first("doctorName").as("doctorName")
                        .first("workTime").as("workTime")
                        .first("reservedNumber").as("reservedNumber")
                        .first("availableNumber").as("availableNumber")
                        .last("amount").as("amount"),
                Aggregation.sort(Sort.Direction.ASC,"workDate")
                );
        List<ScheduleTempVo> aggregate =  mongoTemplate.aggregate(aggregation, Schedule.class, ScheduleTempVo.class).getMappedResults();
        //3.分组整理
        List<ScheduleVo> scheduleVos=new ArrayList<>();
        Map<String, List<ScheduleTempVo>> collect= aggregate.stream()
                .collect(Collectors.groupingBy(ScheduleTempVo::getWorkDate));//按时间分组
        //4.按时间排序
        List<String> dateList=new ArrayList<>(collect.keySet());
        Collections.sort(dateList);
        for (String d : dateList) {
            ScheduleVo scheduleVo=new ScheduleVo();
            String date =d;
            List<ScheduleTempVo> value = collect.get(d);//从数组中拿数据
            value.stream().forEach(s->{//处理上、下午排版
                if (s.getWorkTime()==0){
                    scheduleVo.setAm(new ScheduleParam(s.getReservedNumber(),s.getAvailableNumber(),s.getAmount()));
                }
                if (s.getWorkTime()==1){
                    scheduleVo.setPm(new ScheduleParam(s.getReservedNumber(),s.getAvailableNumber(),s.getAmount()));
                }
            });
            scheduleVo.setDoctorName(doctorName);
            scheduleVo.setWorkDate(date);
            scheduleVos.add(scheduleVo);
        }
        //5.获取数据时间范围
        String first_date = scheduleVos.get(0).getWorkDate();
        String last_date = scheduleVos.get(scheduleVos.size()-1).getWorkDate();
        Date first_day_of_week = null;
        Date last_day_of_week = null;
        try {
            first_day_of_week=getFirstDayOfWeek(first_date);
            last_day_of_week=getLastDayOfWeek(last_date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        map.put("scheduleVos",scheduleVos);
        map.put("first_day_of_week",first_day_of_week);
        map.put("last_day_of_week",last_day_of_week);
        return map;
    }
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) throws ParseException {
        Map<String, Object> result = new HashMap<>();
        //获取预约规则
        Hospital hospital = hospitalService.getByHospitalCode(hoscode);
        if(null == hospital) {
            throw new AppointmentException(ResultCodeEnum.DATA_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();

        //获取可预约日期分页数据
        IPage iPage = this.getListDate(page, limit, bookingRule);
        //当前页可预约日期
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateList=new ArrayList<>();
        iPage.getRecords().stream().forEach(s->dateList.add(sdf.format(s)));
        //获取可预约日期科室剩余预约数
        Criteria criteria = Criteria.where("hospitalCode").is(hoscode).and("departmentCode").is(depcode).and("workDate").in(dateList);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")//分组字段
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleVoList = aggregationResults.getMappedResults();
        //获取科室剩余预约数

        //合并数据 将统计数据ScheduleVo根据“安排日期”合并到BookingRuleVo
        Map<String, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(scheduleVoList)) {
            scheduleVoMap = scheduleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }
        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for(int i=0, len=dateList.size(); i<len; i++) {
            String date = dateList.get(i);

            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            if(null == bookingScheduleRuleVo) { // 说明当天没有排班医生
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            DateTime.Property dayOfWeek = new DateTime(date).dayOfWeek();
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek.getAsText());

            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i == len-1 && page == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if(i == 0 && page == 1) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if(stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        final Hospital byHospitalCode = hospitalService.getByHospitalCode(hoscode);
        //医院名称
        baseMap.put("hospitalName", byHospitalCode!=null?byHospitalCode.getHospitalName():"");
        //科室
        Department department =departmentService.getDepartmentByHospitalCodeAndDepartmentCode(hoscode, depcode);
        //大科室名称
        baseMap.put("bigName", department.getBigName());
        //科室名称
        baseMap.put("departmentCode", department.getDepartmentCode());
//月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
//放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
//停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }


    /**
     * 获取可预约日期分页数据
     */
    private IPage<Date> getListDate(int page, int limit, BookingRule bookingRule) {
//当天放号时间
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
//预约周期
        int cycle = bookingRule.getCycle();
//如果当天放号时间已过，则预约周期后一天为即将放号时间，周期加1
        if(releaseTime.isBeforeNow()) cycle += 1;
//可预约所有日期，最后一天显示即将放号倒计时
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
//计算当前预约日期
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }
//日期分页，由于预约周期不一样，页面一排最多显示7天数据，多了就要分页显示
        List<Date> pageDateList = new ArrayList<>();
        int start = (page-1)*limit;
        int end = (page-1)*limit+limit;
        if(end >dateList.size()) end = dateList.size();
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page, 7, dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;
    }
    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }
    @Override
    public List<BookingVo> getDetailSchedule(String hoscode, String depcode, String workDate) {
        //创建Schedule对象
        Schedule schedule = new Schedule();
        schedule.setHospitalCode(hoscode);
        schedule.setDepartmentCode(depcode);
        schedule.setWorkDate(workDate);
        //创建Example对象，数据库条件查询
        ExampleMatcher matcher=ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        Example<Schedule> example=Example.of(schedule,matcher);
        List<Schedule> all = scheduleRepository.findAll(example);
        List<BookingVo> bookingVos=new ArrayList<>();
        all.stream().forEach(s->{
            BookingVo bookingVo=new BookingVo();
            BeanUtils.copyProperties(s,bookingVo);
            bookingVos.add(bookingVo);
        });
        return bookingVos;
    }

    @Override
    public Schedule getById(String scheduleId) {
        Schedule schedule = scheduleRepository.findById(Long.parseLong(scheduleId)).get();
        if (schedule!=null){
            Hospital hospital=hospitalRepository.getHospitalByHospitalCode(schedule.getHospitalCode());
            Department department=departmentRepository.getDepartmentByDepartmentCode(schedule.getDepartmentCode());
            //计算当前预约日期为周几
            DateTime.Property dayOfWeek = new DateTime(schedule.getWorkDate()).dayOfWeek();
            String asText = dayOfWeek.getAsText();
            Map<String,Object> param=new HashMap<>();
            param.put("hospitalName",hospital==null?null:hospital.getHospitalName());
            param.put("departmentName",department==null?null:department.getDepartmentName());
            param.put("dayOfWeek",asText);
            schedule.setParam(param);
            return schedule;
        }
        return null;
    }

    @Override
    public ScheduleOrderVo getScheduleOrderVo(Long scheduleId) {
        ScheduleOrderVo scheduleOrderVo=new ScheduleOrderVo();
        Schedule schedule = baseMapper.selectById(scheduleId);
        if (schedule==null){
            throw new AppointmentException(ResultCodeEnum.PARAM_ERROR);
        }
        BeanUtils.copyProperties(schedule,scheduleOrderVo);
        Hospital hospital=hospitalService.getHospitalByHospitalCode(schedule.getHospitalCode());
        if (hospital==null){
            throw new AppointmentException(ResultCodeEnum.PARAM_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        Department department=departmentService.getDepartmentByDepartmentCode(schedule.getDepartmentCode());
        if (department==null){
            throw new AppointmentException(ResultCodeEnum.PARAM_ERROR);
        }
        scheduleOrderVo.setReserveDate(new DateTime(schedule.getWorkDate()).toDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setHospitalName(hospital.getHospitalName());
        scheduleOrderVo.setDepartmentName(department.getDepartmentName());
        scheduleOrderVo.setHosScheduleId(scheduleId.toString());
        //scheduleOrderVo.setAmount(schedule.getAmount());
        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());
        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());
        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }

    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        //主键一致就是更新
        scheduleRepository.save(schedule);
    }

    /**
     * 取得当前日期所在周的第一天
     *
     * @param date
     * @return
     */
    public static Date getFirstDayOfWeek(String date) throws ParseException {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse(date);
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(parse);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
        return c.getTime ();
    }
    /**
     * 取得当前日期所在周的最后一天
     *
     * @param date
     * @return
     */
    public static Date getLastDayOfWeek(String date) throws ParseException {
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse(date);
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(parse);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
        return c.getTime();
    }
}
